﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Common;
using Wuqi.Webdiyer;
using Mang24k99.Model.COMM;
using Mang24k99.Business.COMM;

namespace Mang24k99.Web.TreeView
{
    public partial class TreeMenu : System.Web.UI.Page
    {
        protected string RootPath = VirtualPathUtility.ToAbsolute("~/");
        string _AspNetCostumHtmlName = "AspNetCostumHtmlName";
        public string AspNetCostumHtml
        {
            get
            {
                return ViewStateHelper.GetString(this.ViewState, _AspNetCostumHtmlName);
            }
            set
            {
                ViewStateHelper.SetViewState(this.ViewState, value, _AspNetCostumHtmlName);
            }
        }
        string _AddName = "Add";
        string _ModifyName = "Modify";
        string _NavTextName = "NavText";
        /// <summary>
        /// 分页的名称
        /// </summary>
        string _PageIndexName = "pageIndex";
        /// <summary>
        /// 操作的名称
        /// </summary>
        string _OpName = "op";
        /// <summary>
        /// 主键的名称
        /// </summary>
        string _IDName = "ID";
        /// <summary>
        /// Gets or sets the nav text.(保存lblNav.text的初始值)
        /// </summary>
        /// <value>The nav text.</value>
        public string NavText
        {
            get
            {
                return ViewStateHelper.GetString(ViewState, _NavTextName);
            }
            set
            {
                ViewStateHelper.SetViewState(ViewState, value, _NavTextName);
            }
        }
        /// <summary>
        /// Gets or sets the index of the page.(保存修改时当前页)
        /// </summary>
        /// <value>The index of the page.</value>
        public int? PageIndex
        {
            get
            {
                return ViewStateHelper.GetInt(ViewState, _PageIndexName);
            }
            set
            {
                ViewStateHelper.SetViewState(ViewState, value, _PageIndexName);
            }
        }
        /// <summary>
        /// Gets or sets the primary ID.(主键id)
        /// </summary>
        /// <value>The primary ID.</value>
        public int? PrimaryID
        {
            get
            {
                return ViewStateHelper.GetInt(ViewState, _IDName);
            }
            set
            {
                ViewStateHelper.SetViewState(ViewState, value, _IDName);
            }
        }
        /// <summary>
        /// Gets or sets the op.(操作符)
        /// </summary>
        /// <value>The op.</value>
        public string Op
        {
            get
            {
                return ViewStateHelper.GetString(ViewState, _OpName);
            }
            set
            {
                ViewStateHelper.SetViewState(ViewState, value, _OpName);
            }
        }


        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["no"] != null)
                {
                    string treeno = Request.QueryString["no"].ToString();
                    ddlKtCommTreeconfig.SelectedValue = treeno;
                }
                InitialParameter();

            }
        }

        /// <summary>
        /// Binds the ASP net pager.(绑定分页控件)
        /// </summary>
        private void BindAspNetPager()
        {
            AspNetPager aspNetPager = this.AspNetPager1;
            int treeno = Convert.ToInt32(ddlKtCommTreeconfig.SelectedValue);
            int RecordCount = BKtCommTreemenu.Count(treeno);
            aspNetPager.RecordCount = RecordCount;
            aspNetPager.CustomInfoHTML = string.Format(this.AspNetCostumHtml, aspNetPager.PageCount);
            if (!IsPostBack)
            {
                int pageIndex;
                try
                {
                    pageIndex = int.Parse(this.Request.QueryString["pageIndex"]);
                    this.AspNetPager1.CurrentPageIndex = pageIndex;

                }
                catch (Exception)
                {
                }
            }
        }
        /// <summary>
        /// Binds the reapert.(绑定列表控件)
        /// </summary>
        private void BindReapert()
        {
            int treeno = Convert.ToInt32(ddlKtCommTreeconfig.SelectedValue);
            AspNetPager aspNetPager = this.AspNetPager1;
            Repeater repeater = this.Repeater1;
            int maxRecord = aspNetPager.PageSize;
            int startRecord = aspNetPager.StartRecordIndex - 1;
            object dataSource = BKtCommTreemenu.FindALLSliced(startRecord, maxRecord,treeno);
            repeater.DataSource = dataSource;
            repeater.DataBind();
        }
        /// <summary>
        /// Handles the PageChanged event of the AspNetPager1 control.(列表改变时候)
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindAspNetPager();
            BindReapert();
        }
        /// <summary>
        /// Handles the PreRender event of the Repeater1 control.(列表程序之前)
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Repeater1_PreRender(object sender, EventArgs e)
        {
            //Repeater repeater = (Repeater)sender;
            //IEnumerable repeaterObject=repeater.Items;
            //集体加客户端属性
            //PageOp.SetRepeaterAttributes(repeaterObject, "btnDelete", "onclick", "return ConfirmDelete()");
        }
        /// <summary>
        /// Handles the ItemCommand event of the Repeater1 control.(列表控件字段按钮事件)
        /// </summary>
        /// <param name="source">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.RepeaterCommandEventArgs"/> instance containing the event data.</param>
        protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            Button btnSource = e.CommandSource as Button;//事件按钮
            Button btnDelete = e.Item.FindControl("btnDelete") as Button;//删除按钮
            Button btnModify = e.Item.FindControl("btnModify") as Button;
            object id;
            try
            {
                id = int.Parse(e.CommandArgument.ToString());
            }
            catch (Exception)
            {
                //转换失败忽略
                return;
            }
            if (btnSource.CommandName == btnDelete.CommandName)//若为删除按钮
            {
                Delete(id);
                Op = _AddName;
                MessageBox.Redirect(this, GetListUrl(this.AspNetPager1.CurrentPageIndex));
            }
            if (btnSource.CommandName == btnModify.CommandName)//为修改按钮
            {
                Op = _ModifyName;
                PrimaryID = TypeHelper.GetInt(id);
                PageIndex = this.AspNetPager1.CurrentPageIndex;
                BindData();
            }
        }
        protected void Delete(object id)
        {
            MKtCommTreemenu mKtCommTreemenu = BKtCommTreemenu.Find(id);
            if (mKtCommTreemenu != null)
            {
                BKtCommTreemenu.Delete(mKtCommTreemenu);
            }
        }
        protected void lnkbtnAdd_Click(object sender, EventArgs e)
        {
            GoUrl(_AddName);
        }
        private void GoUrl(string op)
        {
            string url = GetUrl(op);
            Response.Redirect(url, true);
        }
        private string GetUrl(string op)
        {
            int pageIndex = this.AspNetPager1.CurrentPageIndex;
            string url = "Edit.aspx" + "?" + "pageIndex=" + pageIndex + "&" + "op=" + op;
            return url;
        }
        protected void lnkbtnList_Click(object sender, EventArgs e)
        {
            GoServerListUrl(1);

        }
        /// <summary>
        /// Initials the parameter.(接受必要参数,无参数退出)
        /// </summary>
        private void InitialParameter()
        {
            if (string.IsNullOrEmpty(Op))
            {
                Op = _AddName;
            }
            NavText = this.lblNav.Text;
            txtMenuNO.Text = (MKtCommTreemenu.GetMaxNO() + 1).ToString();
            //PageIndex = RequestHelper.GetInt(this, _PageIndexName);
            //PrimaryID = RequestHelper.GetInt(this, _IDName);
            //if (!PageIndex.HasValue)
            //{
            //    Response.End();
            //}
            BindData();
        }
        /// <summary>
        /// Binds the data.(绑定基础数据)
        /// </summary>
        private void BindData()
        {
            this.AspNetCostumHtml = this.AspNetPager1.CustomInfoHTML;
            
            if (StringHelper.Compare(Op, _AddName))
            {
                BindDDL();
                AspNetPager1_PageChanged(null, null);
                this.lblNav.Text = string.Format(NavText, "新增");
                this.btnSave.Text = "新 增";
            }
            else if (StringHelper.Compare(Op, _ModifyName))
            {
                if (!PrimaryID.HasValue)
                {
                    Response.End();
                }
                this.btnSave.Text = "修 改";
                SetNavTextToModify();
                BindEdit();
            }
            else
            {
                Response.End();
            }
        }
        /// <summary>
        /// Sets the nav text to modify.
        /// </summary>
        private void SetNavTextToModify()
        {
            this.lblNav.Text = string.Format(NavText, "修改");
        }
        /// <summary>
        /// Binds the DDL.(绑定ddl)
        /// </summary>
        private void BindDDL()
        {
            IList<MKtCommTreeconfig> modelsKtCommTreeconfig = BKtCommTreeconfig.FindAll();
            MKtCommTreeconfig valueKtCommTreeconfig = new MKtCommTreeconfig();
            this.ddlKtCommTreeconfig.DataSource = modelsKtCommTreeconfig;
            this.ddlKtCommTreeconfig.DataTextField = "TreeName";
            this.ddlKtCommTreeconfig.DataValueField = "TreeNO";
            this.ddlKtCommTreeconfig.DataBind();
            int typecode = 312;
            IList<MKtCommCodeList> codelist = BKtCommCodeList.FindByTypeCode(typecode);
            ddlOprateType.DataSource = codelist;
            ddlOprateType.DataTextField = "CODE_CNAME";
            ddlOprateType.DataValueField = "CODE_NO";
            this.ddlOprateType.DataBind();
        }
        /// <summary>
        /// Binds the edit.(绑定编辑页面)
        /// </summary>
        private void BindEdit()
        {
            MKtCommTreemenu modelKtCommTreemenu = BKtCommTreemenu.Find(PrimaryID);
            WebHelper.SetControlValue(modelKtCommTreemenu, txtMenuNO);
            txtMenuNO.Enabled = false;
            ddlKtCommTreeconfig.Enabled = false;
            WebHelper.SetControlValue(modelKtCommTreemenu, txtDisplayName);
            ddlOprateType.SelectedValue = modelKtCommTreemenu.MKtCommCodelist.CODE_NO.ToString();
            WebHelper.SetControlValue(modelKtCommTreemenu, txtLinkAddr);
            WebHelper.SetControlValue(modelKtCommTreemenu, txtLinkRef);
            ListItem ddlSelectedKtCommTreeconfig = ddlKtCommTreeconfig.Items.FindByValue(TypeHelper.GetString(modelKtCommTreemenu.MKtCommTreeconfig.TreeNO));
            if (ddlSelectedKtCommTreeconfig != null)
            {
                ddlKtCommTreeconfig.SelectedIndex = -1;
                ddlSelectedKtCommTreeconfig.Selected = true;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string msg = "";
            #region 接受操作参数
            bool isAdd = false;
            if (StringHelper.Compare(Op, _AddName))
            {
                isAdd = true;
            }
            else if (StringHelper.Compare(Op, _ModifyName))
            {
                isAdd = false;
            }
            else
            {
                return;
            }
            #endregion
            MKtCommTreeconfig mKtCommTreeconfig = BKtCommTreeconfig.Find(TypeHelper.GetInt(ddlKtCommTreeconfig.SelectedValue));
            if (txtDisplayName.Text.Trim()=="")
            {
                msg = "菜单显示名不能为空！";
                MessageBox.Show(this,msg);
                return;
            }
            #region 根据操作选项创建实例
            MKtCommTreemenu modelKtCommTreemenu;
            if (isAdd)
            {
                modelKtCommTreemenu = new MKtCommTreemenu();
            }
            else
            {
                modelKtCommTreemenu = BKtCommTreemenu.Find(PrimaryID);
                if (modelKtCommTreemenu == null)
                {
                    return;
                }
            }
            #endregion
            modelKtCommTreemenu.MKtCommTreeconfig = mKtCommTreeconfig;
            WebHelper.SetModelValue(modelKtCommTreemenu, txtMenuNO);
            WebHelper.SetModelValue(modelKtCommTreemenu, txtDisplayName);

            int oprateType = Convert.ToInt32(ddlOprateType.SelectedValue);
            MKtCommCodeList codelist = MKtCommCodeList.Select(oprateType);
            modelKtCommTreemenu.MKtCommCodelist = codelist;
            WebHelper.SetModelValue(modelKtCommTreemenu, txtLinkAddr);
            WebHelper.SetModelValue(modelKtCommTreemenu, txtLinkRef);
            Castle.Components.Validator.RunWhen runWhen = Castle.Components.Validator.RunWhen.Update;
            if (isAdd)
            {
                runWhen = Castle.Components.Validator.RunWhen.Insert;
            }
            bool isSuccess = modelKtCommTreemenu.IsValid(runWhen);
            if (!isSuccess)
            {
                msg = ActiveRecordValidationBaseHelper.GetErrorMsg(modelKtCommTreemenu);
                MessageBox.Show(this, msg);
                return;
            }
            if (isAdd)
            {
                msg = "添加成功";
                BKtCommTreemenu.Create(modelKtCommTreemenu);
                MessageBox.ShowAndRedirect(this, msg, GetListUrl(0));
            }
            else
            {
                BKtCommTreemenu.Update(modelKtCommTreemenu);
                msg = "修改成功";
                MessageBox.ShowAndRedirect(this, msg, GetListUrl(PageIndex));
            }
        }
        protected void btnReturn_Click(object sender, EventArgs e)
        {

            if (StringHelper.Compare(Op, _AddName))
            {
                MessageBox.Redirect(this, GetListUrl(this.AspNetPager1.CurrentPageIndex));
            }
            else
            {
                MessageBox.Redirect(this, GetListUrl(PageIndex));
            }
        }
        private void GoServerListUrl(int? pageIndex)
        {
            string url = GetListUrl(pageIndex);
            Response.Redirect(url, true);
        }
        private string GetListUrl(int? pageIndex)
        {
            string op = "?" + "" + _PageIndexName + "=" + pageIndex;
            string url = "TreeMenu.aspx" + op;
            return url;
        }
        public string GetType(int type)
        {
            MKtCommCodeList codelist = MKtCommCodeList.Select(type);
            return codelist.CODE_CNAME;
        }

        protected void ddlKtCommTreeconfig_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindAspNetPager();
            BindReapert();
        }
    }
}
